package com.alan.camunda.boot.groovymod.compiled;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import lombok.SneakyThrows;

/**
 * 缓存 Script 对象
 */
public class CompiledDemo3 {

    private static GroovyShell shell = new GroovyShell();

    // 编译并缓存脚本
    public static Script compileScript(String script) {
        return shell.parse(script);
    }

    // 执行脚本
    public static Object executeScript(Script script, Binding binding) {
        script.setBinding(binding);
        return script.run();
    }

    @SneakyThrows
    public static void main(String[] args) {
        // 定义脚本
        String script = """
            import static com.alan.camunda.boot.util.StringFunctions.*
            def bizLogic() {
                return "Hello, " + name
            }
            return bizLogic()
        """;


        Script compiledScript = compileScript(script);
        // 使用 New Instance 构造的对象进行计算
        Script newSp = compiledScript.getClass().newInstance();

        // 绑定变量
        Binding binding = new Binding();
        binding.setVariable("name", "Alex");

        // 执行脚本
        Object result = executeScript(newSp, binding);

        // 输出结果
        System.out.println("Groovy script result: " + result);
    }


}
